/*
 * @Description:
 * @Author: Cxy
 * @Date: 2024-02-27 10:00:22
 * @LastEditors: Cxy
 * @LastEditTime: 2024-09-05 15:36:10
 * @FilePath: \xy-admin\play\src\stores\config\utils.ts
 */
import { hexToRgb, hslToRgb, rgbToHsl } from '@/utils/color'

const colorNum = [2, 0, -3, -5, -7, -8, -9]
export const colorConver = (color: string, type: string, darkLight: string) => {
  const hsl = rgbToHsl(hexToRgb(color))
  const isDark = darkLight === 'dark'
  let stepUp = isDark ? 5 : 3.6
  if (isDark && hsl[2] - 9 * stepUp < 0) stepUp = Math.floor(hsl[2] / 9)
  if (!isDark && hsl[2] + 9 * stepUp > 100) stepUp = Math.floor((100 - hsl[2]) / 9)
  const stepDown = 10
  const hueShift = 5
  const baseShadeStop = 0
  const saturationShift = 4

  return colorNum.reduce((prev: any, c, i) => {
    const distance = baseShadeStop - (isDark ? -c : c)
    const direction = distance === 2 ? stepDown : stepUp

    const lightness = Math.min(Math.max(hsl[2] + direction * distance, 0), 100)

    let hue = hsl[0]
    if (hueShift) {
      const hsh = Math.abs((hueShift * distance) / 10)
      hue = hue + (hue + hsh >= 360 ? -hsh : hsh)
    }

    let saturation = hsl[1]
    if (saturationShift) {
      const hsh = Math.abs((saturationShift * distance) / 5)
      saturation = saturation + (saturation + hsh >= 100 ? -hsh : hsh)
    }

    prev[`--color-${type}${colorNum[i] ? `-${colorNum[i] === 2 ? 'dark' : 'light'}-${Math.abs(colorNum[i])}` : ''}`] =
      String(hslToRgb([hue, saturation, lightness]))
    return prev
  }, {})
}

export const createStyle = (css: Record<string, string | null>) => {
  const elStyle = document.documentElement.style
  Object.entries(css).forEach(([key, val]: any) => {
    val ? elStyle.setProperty(key, val) : elStyle.removeProperty(key)
  })
}

// const colorType = ['primary', 'success', 'warning', 'danger', 'error', 'info']
/* 可拓展到其他类型主题色 */
export const changeThemeDarkLight = (darkLight: string, color: string) =>
  createStyle(colorConver(color, 'primary', darkLight))

export const matchSize = (key: string) => new RegExp(`^--${key}-(?!.*color).*$`, 'i')

export const matchColor = (key: string) => new RegExp(`^--${key}-.*color-.*$`, 'i')
